package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MakeFriendManager {

    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    UserLocationService userLocationService;

    @DubboReference
    QuestionService questionService;

    public ResponseEntity findTodayBest() {
        //1.获取当前用户id
        //2.远程调用service查询今日佳人
        RecommendUser recommendUser = recommendUserService.findTodayBest(UserHolder.get().getId());

        //2.1 目前处于开发阶段,刚注册的用户暂时还没有推荐用户,我们就模拟一个
        if (recommendUser == null) {
            recommendUser = new RecommendUser();

            recommendUser.setUserId(1L);
            recommendUser.setScore(RandomUtil.randomDouble(95,100));
        }

        //3.获取佳人id,查询userInfo
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

        //4.封装vo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());//缘分值

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findRecommendUserByPage(Integer pageNum, Integer pageSize) {
        //1.获取当前用户id
        //2.远程调用service查询当前页的数据
        PageBeanVo pageBeanVo = recommendUserService.findByPage(UserHolder.get().getId(), pageNum, pageSize);

        //3.获取pageBeanVo中推荐用户list
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();

        //4.遍历用户list,获取每个用户id,查询userInfo,封装成RecommendUserVo,将每个vo放入voList中
        List<RecommendUserVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(recommendUser -> {
                UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(recommendUser.getScore().longValue());

                voList.add(vo);
            });
        }

       /* List<RecommendUserVo> voList = items.stream().map(recommendUser -> {
            UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

            RecommendUserVo vo = new RecommendUserVo();
            vo.setUserInfo(userInfo);
            vo.setFateValue(recommendUser.getScore().longValue());
            return vo;
        }).collect(Collectors.toList());*/

        //5.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);

        //6.将pageBeanVo返回
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findPersonalInfo(Long recommendUserId) {
        //1.远程调用service查询推荐用户的userInfo
        UserInfo userInfo = userInfoService.findById(recommendUserId);

        //2.远程调用service查询俩用户的缘分值
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(UserHolder.get().getId(), recommendUserId);
        //注意:推荐用户有可能不存在,若不存在设置一个默认值
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(90,99));
        }

        //3.封装recommendUserVo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findVisitorsTop5() {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.获取上次访问时间(注意新用户)
        String lastAccessTimeStr = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        Long lastAccessTime;

        if (lastAccessTimeStr==null) {
            //将1970年赋值给它
            lastAccessTime = new Date(0).getTime();
        }else {
            lastAccessTime = Long.parseLong(lastAccessTimeStr);
        }

        //3.远程调用service获取最近访客list
        List<Visitor> visitorList = visitorService.findVisitorsTop5(userId, lastAccessTime);

        //4.遍历访客list,获取每个访客id,查询其userInfo,将其封装成VisitorVo,将每个vo放入voList中
        List<VisitorVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(visitorList)) {
            visitorList.forEach(visitor -> {
                UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());

                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(visitor.getScore().longValue());

                voList.add(vo);
            });
        }

        //5.将当前的访问时间存放到redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME+userId,System.currentTimeMillis()+"");

        //6.返回voList
        return ResponseEntity.ok(voList);
    }

    public void saveUserLocation(Double longitude, Double latitude, String addrStr) {
        userLocationService.save(longitude,latitude,addrStr,UserHolder.get().getId());
    }

    public ResponseEntity searchNear(String gender, Long distance) {
        Long userId = UserHolder.get().getId();

        //1.远程调用service获取附近用户idList
        List<Long> idList = userLocationService.searchNear(userId, distance);

        //2.遍历idList,获取每个用户userInfo,将userInfo封装成nearUserVo,将每个vo放入voList中
        List<NearUserVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(idList)) {
            for (Long id : idList) {
                //排除自己
                if (userId.equals(id)) {
                    continue;
                }

                //获取每个userInfo
                UserInfo userInfo = userInfoService.findById(id);

                //判断:性别
                if (!userInfo.getGender().equals(gender)) {
                    continue;
                }

                NearUserVo vo = new NearUserVo();
                vo.setUserId(id);
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                voList.add(vo);
            }
        }
        //3.返回voList
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity findStrangerQuestion(Long userId) {
        //1.远程调用service查询陌生人问题
        Question question = questionService.findByUserId(userId);

        //2.若不存在的话,设置一个默认问题
        if (question == null) {
            question = new Question();
        }

        //3.返回问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
}
